/*
 * 本类作用：mina框架:工具类
 * 
 * 作者：袁小杰
 * 博客：http://blog.csdn.net/undoner
 * GIT：https://git.oschina.net/undoner
 * QQ：15137281
 * 
 */
package org.mina.server.codec;

import org.apache.mina.core.buffer.IoBuffer;

public class MsgUtils {
	
	/**
	 * 整型转byte[]
	 * */
	public static byte[] intToByte(int i) {
		byte[] abyte = new byte[4];
		abyte[0] = (byte) (0xff & i);
		abyte[1] = (byte) ((0xff00 & i) >> 8);
		abyte[2] = (byte) ((0xff0000 & i) >> 16);
		abyte[3] = (byte) ((0xff000000 & i) >> 24);
		return abyte;
	}

	/**
	 * byte[]转整型
	 * */
	public static int bytesToInt(byte[] bytes) {
		int addr = bytes[0] & 0xFF;
		addr |= ((bytes[1] << 8) & 0xFF00);
		addr |= ((bytes[2] << 16) & 0xFF0000);
		addr |= ((bytes[3] << 24) & 0xFF000000);
		return addr;
	}
	/**  
	* 将byte[]转换成string    
	* @param butBuffer  
	*/  
	public static String byteToString(byte [] b)   
	{   
	       StringBuffer stringBuffer = new StringBuffer();   
	       for (int i = 0; i < b.length; i++)   
	       {   
	           stringBuffer.append((char) b [i]);   
	       }   
	       return stringBuffer.toString();   
	}   
	  
	/**  
	* 将string转换成IoBuffer
	* @param str  
	*/  
	public static IoBuffer stringToIoBuffer(String str)   
	{   
	  
	       byte bt[] = str.getBytes();   
	  
	       IoBuffer ioBuffer = IoBuffer.allocate(bt.length);   
	       ioBuffer.put(bt, 0, bt.length);   
	       ioBuffer.flip();   
	       return ioBuffer;   
	}   
	/**  
	* 将byte转换成IoBuffer    
	* @param str  
	*/  
	public static IoBuffer byteToIoBuffer(byte [] bt,int length)   
	{   
	  
	       IoBuffer ioBuffer = IoBuffer.allocate(length);   
	       ioBuffer.put(bt, 0, length);   
	       ioBuffer.flip();   
	       return ioBuffer;   
	}   
	/**  
	* 将IoBuffer转换成byte    
	* @param str  
	*/  
	public static byte [] ioBufferToByte(Object message)   
	{   
	      if (!(message instanceof IoBuffer))   
	      {   
	          return null;   
	      }   
	      IoBuffer ioBuffer = (IoBuffer)message;   
	      byte[] b = new byte[ioBuffer.limit()];   
	      ioBuffer.get(b);   
	      return b;   
	}   
	/**  
	* 将IoBuffer转换成string    
	* @param butBuffer  
	*/  
	public static String ioBufferToString(Object message)   
	{   
	      if (!(message instanceof IoBuffer))   
	      {   
	        return "";   
	      }   
	      IoBuffer ioBuffer = (IoBuffer) message;   
	      byte[] b = new byte [ioBuffer.limit()];   
	      ioBuffer.get(b);   
	      StringBuffer stringBuffer = new StringBuffer();   
	  
	      for (int i = 0; i < b.length; i++)   
	      {   
	  
	       stringBuffer.append((char) b [i]);   
	      }   
	       return stringBuffer.toString();   
	}  

}
